import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:wuxu_flutter_lianxi/localization/res_string.dart';

///
/// 国际化
///
/// 1.设定语言选项map
/// 2.获取本地语言： locale.languageCode
/// 3.将WxLocalizations装载到Localizations中。ps：Localizations维护了一个数组，用于缓存数据
/// 4.创建继承LocalizationsDelegate的子类
/// 5.将代理设置到根部件中
///

class WxLocalizations{
  final Locale _locale;

  WxLocalizations(this._locale);

  static final Map<String,AbstractResString> _localizationValues = {
    "zh":StringZN(),
    "en":StringEN()
  };

  AbstractResString get _resString {//这里用get是懒加载
    if(_localizationValues.containsKey(_locale.languageCode)){
      return _localizationValues[_locale.languageCode]!;
    }
    return _localizationValues["en"]!;
  }

  ///通过Localizations获取WxLocalizations； 这个就是取缓存好的数据。
  ///那什么时候放进去的？
  ///答：在根部件构建时，将其设置好了
  static WxLocalizations? of(BuildContext context){
    return Localizations.of<WxLocalizations>(context,WxLocalizations);
  }

  static AbstractResString languageResString(BuildContext context){
      return of(context)!._resString;
  }
}

class WxLocalizationsDelegate extends LocalizationsDelegate<WxLocalizations>{
  @override
  bool isSupported(Locale locale) {
    //不论啥语言，都支持~
    return true;
  }

  @override
  Future<WxLocalizations> load(Locale locale) {
    //根据语言类型，创建 WxLocalizations
    
    return SynchronousFuture(WxLocalizations(locale));//SynchronousFuture 将同步操作封为异步，但会立刻返回结果
  }

  @override
  bool shouldReload(covariant LocalizationsDelegate<WxLocalizations> old) {
    //已经通过WxLocalizations 可以进行数据变化了，这里始终为false避免重复刷新界面
    return false;
  }

  //全局代理，单例
  static LocalizationsDelegate<WxLocalizations> delegate = WxLocalizationsDelegate();
}